<?php

/**
 * Created by PhpStorm.
 * User: Short Perton
 * Date: 2016/8/30
 * Time: 11:26
 */
namespace sw\server;

class ChatServer
{

    private $serv;

    public function __construct() {
        $this->serv = new \swoole_server("127.0.0.1", 9501);
        $this->serv->set([
            'work_num' => 8,
            'daemonize' => false,
        ]);

        $this->serv->on('start', [$this, 'onStart']);
        $this->serv->on('connect', [$this, 'onConnect']);
        $this->serv->on('receive', [$this, 'onReceive']);
        $this->serv->on('close', [$this, 'onClose']);
        $this->serv->start();
    }

    public function onStart($serv) {
        echo "Start\n";
    }

    public function onConnect($serv, $fd, $from_id) {
        $msg = Create::user($fd);
        $serv->send($fd, "Hello {$fd}!\n" . $msg);
    }

    public function onReceive($serv, $fd, $from_id, $data) {
        echo "Get Message From Client {$fd}:{$data}\n";
        $serv->send($fd, $data);
    }

    public function onClose($serv, $fd, $from_id) {
        echo "Client {$fd} close connection\n";
    }

}